import { loginAPI } from '@/api/login'
import { getUserInfoAPI, updatePasswordAPI } from '@/api/user'
import router from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  userInfo: {},
  routes: []
}

const mutations = {
  saveToken(state, payload) {
    state.token = payload
  },
  saveUserInfo(state, payload) {
    state.userInfo = payload
  },
  setRoutes(state, payload) {
    state.routes = payload
  }
}

const actions = {
  // 登录
  async loginAction(store, payload) {
    const res = await loginAPI(payload)
    // 给token赋值
    store.commit('saveToken', res)
    // 持久化存储token
    setToken(res)
    // 跳转到首页
    router.push('/')
    // 提示
    Message.success('登录成功')
  },
  // 获取用户信息
  async getUserInfoAction(store) {
    const res = await getUserInfoAPI()
    store.commit('saveUserInfo', res)
    console.log('res --->', res)
  },
  // 退出登陆
  logoutAction(store) {
    store.commit('saveToken', '')
    removeToken()
    store.commit('saveUserInfo', {})
    router.push('/login')
    router.resetRouter()
  },
  // 修改密码
  async updatePasswordAction(store, payload) {
    await updatePasswordAPI(payload)
    Message.success('密码修改成功,请重新登陆')
    store.commit('saveToken', '')
    removeToken()
    store.commit('saveUserInfo', {})
    router.push('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

